package com.guyaogg.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.constant.ProductConstant;
import com.guyaogg.common.to.SkuHasStockVO;
import com.guyaogg.common.to.SkuReductionTo;
import com.guyaogg.common.to.SpuBoundTo;
import com.guyaogg.common.to.es.SkuEsModel;
import com.guyaogg.common.utils.*;
import com.guyaogg.gulimall.product.dao.SpuInfoDao;
import com.guyaogg.gulimall.product.entity.*;
import com.guyaogg.gulimall.product.feign.CouponFeignService;
import com.guyaogg.gulimall.product.feign.SearchFeignService;
import com.guyaogg.gulimall.product.feign.WareFeignService;
import com.guyaogg.gulimall.product.service.*;
import com.guyaogg.gulimall.product.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    private final SpuInfoDescService spuInfoDescService;
    private final SpuImagesService spuImagesService;
    private final AttrService attrService;
    private final ProductAttrValueService productAttrValueService;
    private final SkuInfoService skuInfoService;
    private final SkuImagesService skuImagesService;
    private final SkuSaleAttrValueService skuSaleAttrValueService;
    private final CouponFeignService couponFeignService;
    private final BrandService brandService;
    private final CategoryService categoryService;
    private final WareFeignService wareFeignService;
    private final SearchFeignService searchFeignService;

    public SpuInfoServiceImpl(AttrService attrService, SpuInfoDescService spuInfoDescService, SpuImagesService spuImagesService, ProductAttrValueService productAttrValueService, SkuInfoService skuInfoService, SkuImagesService skuImagesService, SkuSaleAttrValueService skuSaleAttrValueService, CouponFeignService couponFeignService, BrandService brandService, CategoryService categoryService, WareFeignService wareFeignService, SearchFeignService searchFeignService) {
        this.attrService = attrService;
        this.spuInfoDescService = spuInfoDescService;
        this.spuImagesService = spuImagesService;
        this.productAttrValueService = productAttrValueService;
        this.skuInfoService = skuInfoService;
        this.skuImagesService = skuImagesService;
        this.skuSaleAttrValueService = skuSaleAttrValueService;
        this.couponFeignService = couponFeignService;
        this.brandService = brandService;
        this.categoryService = categoryService;
        this.wareFeignService = wareFeignService;
        this.searchFeignService = searchFeignService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * // TODO 高级部分再来完善
     * # @GlobalTransactional 非高并发可以使用，AT 模式，性能不高,保证强一致性
     *
     * @param vo
     *
     */
    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @GlobalTransactional
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO vo) {
        // 保存 Spu 基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        // 保存 Spu 的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        // Spu 的图片集 pms_spu_images
        List<String> images = vo.getImages();

        spuImagesService.saveImages(spuId, images);
        // 保存 Spu 的规格参数 ·pms_product_attr_value·
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrService.getById(attr.getAttrId()).getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuId);
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(collect);
        // Spu 积分信息 -> gulimall_sms sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存 spu 积分信息失败");
        }


        // 保存当前 Spu 对应所有 Sku 信息
        List<Skus> skus = vo.getSkus();
        if (!skus.isEmpty()) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                /*
                 *  private String skuName;
                 *  private BigDecimal price;
                 *  private String skuTitle;
                 *  private String skuSubtitle;
                 */
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                /// sku 基本信息 pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity ->
                        // TODO 没有图片路径的无需保存
                        !StringUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                /// sku 的图片集 pms_sku_images
                skuImagesService.saveBatch(imagesEntities);
                /// sku 的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                /// sku 的优惠满减等信息 -> gulimall_sms sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 检验满减信息的问题
                if (skuReductionTo.getFullCount() >= 0 && skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存 sku 优惠信息失败");
                    }
                }


            });

        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * {
     * page: 1,//当前页码
     * limit: 10,//每页记录数
     * sidx: 'id',//排序字段
     * order: 'asc/desc',//排序方式
     * key: '华为',//检索关键字
     * catelogId: 6,//三级分类id
     * brandId: 1,//品牌id
     * status: 0,//商品状态
     * }
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            String trimKey = key.trim();
            wrapper.and(w -> w.eq("id", trimKey).or().like("spu_name", trimKey));
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && Integer.parseInt(brandId) > 0) {
            wrapper.eq("brand_id", brandId);

        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && Integer.parseInt(catelogId) > 0) {
            wrapper.eq("catalog_id", catelogId);

        }
        log.debug("key:{},brandId:{},status:{},catelogId{}", key, brandId, status, catelogId);
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId 商品 spuId
     */
    @Override
    public void up(Long spuId) {
        // 组装需要的数据
        // 1.查出当前 spuId 对应的所有 sku 信息，品牌名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySkuId(spuId);

        // TODO 查询当前 Sku 所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> attrs = baseAttrs.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attr attr = new SkuEsModel.Attr();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());


        // 2.封装每个 sku 的信息
        if (!skus.isEmpty()) {
            // TODO 查询远程调用是否有库存
            Map<Long, Boolean> stockMap = null;
            try {
                List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
                ToT<List<SkuHasStockVO>> skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
                stockMap = skusHasStock.getData().stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock));

            } catch (Exception e) {
                log.error("库存服务查询异常,原因：{}", e.getMessage());
            }

            // TODO 查询品牌和分类的名字信息  catalogName,brandImg,brandName,
            BrandEntity brandEntity = brandService.getById(skus.get(0).getBrandId());
            CategoryEntity categoryEntity = categoryService.getById(skus.get(0).getCatalogId());

            Map<Long, Boolean> finalStockMap = stockMap;
            List<SkuEsModel> upProducts = skus.stream().map(sku -> {
                SkuEsModel esModel = new SkuEsModel();
                BeanUtils.copyProperties(sku, esModel);
                // price,img ;
                esModel.setSkuPrice(sku.getPrice());
                esModel.setSkuImg(sku.getSkuDefaultImg());
                // hasStock,hotScore,
                // 设置库存信息

                if (finalStockMap == null) {
                    esModel.setHasStock(true);
                } else {
                    esModel.setHasStock(finalStockMap.get(sku.getSkuId()));

                }
                // TODO 热点评分。默认 0；
                esModel.setHotScore(0L);
                esModel.setBrandName(brandEntity.getName());
                esModel.setBrandImg(brandEntity.getLogo());
                esModel.setCatalogName(categoryEntity.getName());
                esModel.setAttrs(attrs);
                //List<Attr>
                return esModel;
            }).collect(Collectors.toList());
            // TODO 5.将数据发送给 es 进行保存
            R r = searchFeignService.productStatusUp(upProducts);
            if(r.getCode() == 0){
                // 远程调用成功
                // TODO 6.改变发布状态
                this.baseMapper.updateSpuStatus(spuId, ProductConstant.ProductUpStatusEnum.SPU_UP.getCode());
            }else {
                // 远程调用失败
                // TODO 7.重复调用？接口幂等性；重试机制;

                // Feign 调用流程
                /*
                1.构造请求数据，将对象转为 json
                2.发送请求进行执行（执行成功后会解码响应数据）
                3.执行请求会有重试机制（默认关闭，默认次数 5 次）

                 */
            }


        }


    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();

        return getById(spuId);
    }


}